package com.efivestar.idm.api.service.lock.protocol.handler;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.repository.EventMapper;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.dto.PowerDto;
import com.efivestar.idm.api.util.ByteUtils;

import io.netty.buffer.ByteBuf;

@Service
public class HeartBeatLockProtocolHandler extends AbstractLockProtocolHandler{

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private EventMapper mapper;

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId){
        int length = buf.readableBytes();
        //跳过指令码，不读取
        buf.skipBytes(1);
//        读取电量字节
        byte powerBt = buf.readByte();
        PowerDto power = ByteUtils.getPower(powerBt);
        //读取imei(设备编号)
        // String lockId = String.valueOf(buf.readCharSequence(length - getDataLenthWithoutDeviceId(), Charset.forName("utf-8")));
        //设置设备的电量和更新时间
        deviceService.updatePower(lockId, power.getPowerPercent());
        Date dateOf2017 = null;
        try {
            dateOf2017 = DateUtils.parseDate("2017-01-01 00:00:00", new String[]{"yyyy-MM-dd HH:mm:ss"});
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //TODO  用 四个字节标识8位数字，这个要和指纹锁确定下实现。
//        Date now = new Date();
//        String secondsStr = String.valueOf((now.getTime() - dateOf2017.getTime())/1000);
//        String returnDate = ByteUtils.bytes2hex(secondsStr.getBytes());
        return ByteUtils.hexToBytes("00");

    }


    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 2;
    }


    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    public String udpHead(){
        return Cons.UDP_HEAD_EF01;
    }

    @Override
    public String udpCommand(){
        return Cons.UDP_COMMAND_HEART_BEAT;
    }


    public static void main(String[] args) {
        Date dateOf2017 = null;
        try {
            dateOf2017 = DateUtils.parseDate("2017-01-01 00:00:00", new String[]{"yyyy-MM-dd HH:mm:ss"});
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date now = new Date();
        String secondsStr = String.valueOf((now.getTime() - dateOf2017.getTime())/1000);
        System.out.println(secondsStr);
    }
}






